/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable max-len */
/* eslint-disable consistent-return */
/**
 * Created by zhangsong on 2019-05-08.
 */
import Power from '@/constants/power';
import Authorized from '@/utils/Authorized';
import InputGroupGrid from '@/components/InputGroupGrid';
import React, { Component } from 'react';
import moment from 'moment';
import {
  Form,
  Input,
  DatePicker,
  Button,
  Radio,
  Upload,
  Icon,
  Spin,
  Modal,
  Row,
  Col,
  Tooltip,
  Select,
  Checkbox,
  message,
  Switch,
} from 'antd';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { formatMessage, FormattedMessage, getLocale } from '@/utils/i18n';
import VaccineReducer from '@/dva/application/vaccine';
import UserReducer from '@/dva/user';
import { ContractorApplication } from '@/constants/routes';
import { WorkCardDefault } from '@/constants/styleConfig';
import PDFPreview from '@/components/PDFPreview';
import { getBase64, getPageQuery } from '@/utils/utils';
import _ from 'lodash';

import Style from './index.module.scss';

const { Namespace, Effects, Reducers } = VaccineReducer;

@connect(
  state => ({
    contractorStore: state[Namespace],
    userStore: state[UserReducer.Namespace],
  }),
  dispatch => ({
    getVaccine: data =>
      dispatch({
        type: `${Namespace}/${Effects.getVaccine}`,
        data,
      }),
    setStateSw: data =>
      dispatch({
        type: `${Namespace}/${Effects.setStateSw}`,
        data,
      }),
    handleSubmit: data =>
      dispatch({
        type: `${Namespace}/${Effects.addVaccine}`,
        data,
      }),
    handleSubmitModify: data =>
      dispatch({
        type: `${Namespace}/${Effects.modifyVaccine}`,
        data,
      }),
  }),
)
@Form.create()
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    const { getVaccine, userStore } = this.props;
    console.log('這裡是什麼數據');
    getVaccine(userStore.currentUser.company_number);
  }

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 显示头像预览
  handlePhotographPreview = async file => {
    if (file.type === 'application/pdf') {
      Modal.info({ title: formatMessage('applicationContractor.tips.noSupportedPDF') });
      return;
    }
    if (!file.url) {
      if (file.response) {
        file.thumbUrl = file.response;
      } else {
        file.thumbUrl = await getBase64(file.originFileObj);
      }
    }

    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleClear = () => {
    const { contractorStore, form } = this.props;
    let { vaccinedetial } = contractorStore;
    form.setFieldsValue({
      vaccination_date1: undefined,
      vaccination_date2: undefined,
      vaccination_date3: undefined,
      vaccination_date4: undefined,
      vaccination_date5: undefined,
    });
    vaccinedetial = {
      companyId: vaccinedetial.companyId,
      disable: vaccinedetial.disable,
      id: vaccinedetial.id,
      vaccinationDate1: null,
      vaccinationDate2: null,
      vaccinationDate3: null,
      vaccinationDate4: null,
      vaccinationDate5: null,
    };
    this.props.setStateSw({
      vaccinedetial,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, handleSubmit, handleSubmitModify, userStore, contractorStore } = this.props;
    const { vaccinedetial, modifycode } = contractorStore;
    form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        console.log('看看这个输出的只', values);

        if (modifycode) {
          handleSubmitModify({
            companyId: userStore.currentUser.company_number,
            disable: vaccinedetial.disable,
            vaccinationDate1: values.vaccination_date1
              ? moment(values.vaccination_date1).format('YYYY-MM-DD')
              : null,
            vaccinationDate2: values.vaccination_date2
              ? moment(values.vaccination_date2).format('YYYY-MM-DD')
              : null,
            vaccinationDate3: values.vaccination_date3
              ? moment(values.vaccination_date3).format('YYYY-MM-DD')
              : null,
            vaccinationDate4: values.vaccination_date4
              ? moment(values.vaccination_date4).format('YYYY-MM-DD')
              : null,
            vaccinationDate5: values.vaccination_date5
              ? moment(values.vaccination_date5).format('YYYY-MM-DD')
              : null,
          });
        } else {
          handleSubmit({
            companyId: userStore.currentUser.company_number,
            disable: this.state.isbools,
            vaccinationDate1: values.vaccination_date1
              ? moment(values.vaccination_date1).format('YYYY-MM-DD')
              : null,
            vaccinationDate2: values.vaccination_date2
              ? moment(values.vaccination_date2).format('YYYY-MM-DD')
              : null,
            vaccinationDate3: values.vaccination_date3
              ? moment(values.vaccination_date3).format('YYYY-MM-DD')
              : null,
            vaccinationDate4: values.vaccination_date4
              ? moment(values.vaccination_date4).format('YYYY-MM-DD')
              : null,
            vaccinationDate5: values.vaccination_date5
              ? moment(values.vaccination_date5).format('YYYY-MM-DD')
              : null,
          });
        }
      }
    });
  };

  handleSaveModalCancel = () => {
    const { history, saveModalCancel } = this.props;
    saveModalCancel();
    history.push(ContractorApplication.list.url);
  };

  previewPdf = () => {
    const { previewPdf } = this.props;
    previewPdf({});
  };

  handlePDFOk = () => {
    const { handPDFModalCancel, history } = this.props;
    handPDFModalCancel();
    history.push(ContractorApplication.list.url);
  };

  handlePDFCancel = () => {
    const { handPDFModalCancel, history } = this.props;
    handPDFModalCancel();
    history.push(ContractorApplication.list.url);
  };

  onSwCheck = (bool, even) => {
    console.log('onSwCheck', bool, even);
    this.setState({
      isModalVisible: true,
      isbools: bool ? 1 : 0,
    });
  };

  onOk = () => {
    const { contractorStore } = this.props;
    const { vaccinedetial } = contractorStore;
    vaccinedetial.disable = this.state.isbools;
    console.log('sssssssss', vaccinedetial, this.state.isbools);
    this.setState({
      isModalVisible: false,
    });
    this.props.setStateSw({
      vaccinedetial,
    });
  };

  onChange = (date, dateString, index) => {
    const { form } = this.props;
    console.log('date, dateString, index', date, index)
    switch (index) {
      case 1:
        if (!date) {
          form.setFieldsValue({
            vaccination_date2: undefined,
            vaccination_date3: undefined,
            vaccination_date4: undefined,
            vaccination_date5: undefined,
          });
        }
        break;
      case 2:
        if (!date) {
          form.setFieldsValue({
            vaccination_date3: undefined,
            vaccination_date4: undefined,
            vaccination_date5: undefined,
          });
        }
        break;
      case 3:
        if (!date) {
          form.setFieldsValue({
            vaccination_date4: undefined,
            vaccination_date5: undefined,
          });
        }
        break;
      case 4:
        if (!date) {
          form.setFieldsValue({
            vaccination_date5: undefined,
          });
        }
        break;
      case 5:
        console.log('5')
        break;

      default:
        break;
    }
  }

  render() {
    const { form, contractorStore = {}, userStore = {} } = this.props;
    const { isModalVisible } = this.state;
    const { getFieldDecorator } = form;
    let headPhotoUpload = true;
    const headPhoto = form.getFieldValue('headPhoto');
    if (headPhoto && Array.isArray(headPhoto) && headPhoto.length > 0) {
      headPhotoUpload = false;
    }
    let annexesUpload = true;
    const annexes = form.getFieldValue('annexes');
    if (annexes && Array.isArray(annexes) && annexes.length > 10) {
      annexesUpload = false;
    }
    console.log(form.getFieldValue('commercialCodeAlias'));
    const { saveLoading, vaccinedetial } = contractorStore;

    const swcheck = vaccinedetial ? (vaccinedetial.disable === 0 ? false : true) : false;
    console.log('vaccinedetialvaccinedetial', vaccinedetial, swcheck);
    return (
      <PageHeaderWrapper>
        <Spin spinning={!!saveLoading} size="large">
          <div className={`${Style.body} contractor-add-wrapper`}>
            <Modal
              title={formatMessage('applicationCommon.workerCard.vaccinations_date')}
              visible={isModalVisible}
              onOk={() => this.onOk()}
              onCancel={() => this.setState({ isModalVisible: false })}
            >
              {swcheck ? (
                <p>{formatMessage('applicationCommon.workerCard.isvaccina')}</p>
              ) : (
                <p>{formatMessage('applicationCommon.workerCard.isvaccinas')}</p>
              )}
            </Modal>
            <Form labelAlign="right" onSubmit={this.handleSubmit}>
              <div className={Style.part}>
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'end',
                    alignItems: 'center',
                    paddingRight: 30,
                  }}
                >
                  <Button style={{ marginRight: 20 }} htmlType="button" onClick={this.handleClear}>
                    {formatMessage('button.clear')}
                  </Button>
                  <Button type="primary" htmlType="submit">
                    {formatMessage('button.save')}
                  </Button>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', paddingLeft: 10 }}>
                  <span style={{ color: '#000', marginRight: 5 }}>
                    {formatMessage('applicationCommon.workerCard.vaccinations_date')}:
                  </span>
                  <Switch
                    onChange={this.onSwCheck}
                    checkedChildren="开启"
                    unCheckedChildren="关闭"
                    checked={swcheck}
                  />
                </div>
                <div className={Style.main}>
                  <div className={Style.detailWrapper}>
                    <div className={Style.table}>
                      {/* 疫苗日期 */}
                      {/* <div className={Style.row}>
                        <FormattedMessage id="applicationCommon.workerCard.vaccinations_date" />
                      </div> */}
                      <div className={`${Style.row} ${Style.column2}`}>
                        <div>
                          <Form.Item
                            label={formatMessage('applicationCommon.workerCard.vaccinations_date1')}
                          >
                            {getFieldDecorator('vaccination_date1', {
                              initialValue: _.get(vaccinedetial, 'vaccinationDate1')
                                ? moment(vaccinedetial.vaccinationDate1)
                                : null,

                              rules: [
                                {
                                  required: false,
                                  message: formatMessage(
                                    'applicationCommon.workerCard.expiredDate.vaccineErr',
                                  ),
                                },
                              ],
                            })(<DatePicker onChange={(date, dateString) => this.onChange(date, dateString, 1)} format={formatMessage('datetimeFormat.date')} />)}
                          </Form.Item>
                        </div>
                        <div>
                          <Form.Item
                            label={formatMessage('applicationCommon.workerCard.vaccinations_date2')}
                          >
                            {getFieldDecorator('vaccination_date2', {
                              initialValue: _.get(vaccinedetial, 'vaccinationDate2')
                                ? moment(vaccinedetial.vaccinationDate2)
                                : null,
                              rules: [
                                {
                                  required: false,
                                  message: formatMessage(
                                    'applicationCommon.workerCard.expiredDate.vaccineErr',
                                  ),
                                },
                              ],
                            })(
                              <DatePicker
                                onChange={(date, dateString) => this.onChange(date, dateString, 2)}
                                disabled={!form.getFieldValue('vaccination_date1')}
                                format={formatMessage('datetimeFormat.date')}
                              />,
                            )}
                          </Form.Item>
                        </div>
                        <div>
                          <Form.Item
                            label={formatMessage('applicationCommon.workerCard.vaccinations_date3')}
                          >
                            {getFieldDecorator('vaccination_date3', {
                              initialValue: _.get(vaccinedetial, 'vaccinationDate3')
                                ? moment(vaccinedetial.vaccinationDate3)
                                : null,
                              rules: [
                                {
                                  required: false,
                                  message: formatMessage(
                                    'applicationCommon.workerCard.expiredDate.vaccineErr',
                                  ),
                                },
                              ],
                            })(
                              <DatePicker
                                onChange={(date, dateString) => this.onChange(date, dateString, 3)}
                                disabled={
                                  !(
                                    form.getFieldValue('vaccination_date1') &&
                                    form.getFieldValue('vaccination_date2')
                                  )
                                }
                                format={formatMessage('datetimeFormat.date')}
                              />,
                            )}
                          </Form.Item>
                        </div>
                      </div>
                      <div className={`${Style.row} ${Style.column3}`}>
                        <div>
                          <Form.Item
                            label={formatMessage('applicationCommon.workerCard.vaccinations_date4')}
                          >
                            {getFieldDecorator('vaccination_date4', {
                              initialValue: _.get(vaccinedetial, 'vaccinationDate4')
                                ? moment(vaccinedetial.vaccinationDate4)
                                : null,
                              rules: [
                                {
                                  required: false,
                                  message: formatMessage(
                                    'applicationCommon.workerCard.expiredDate.vaccineErr',
                                  ),
                                },
                              ],
                            })(
                              <DatePicker
                                onChange={(date, dateString) => this.onChange(date, dateString, 4)}
                                disabled={
                                  !(
                                    form.getFieldValue('vaccination_date1') &&
                                    form.getFieldValue('vaccination_date2') &&
                                    form.getFieldValue('vaccination_date3')
                                  )
                                }
                                format={formatMessage('datetimeFormat.date')}
                              />,
                            )}
                          </Form.Item>
                        </div>
                        <div>
                          <Form.Item
                            label={formatMessage('applicationCommon.workerCard.vaccinations_date5')}
                          >
                            {getFieldDecorator('vaccination_date5', {
                              initialValue: _.get(vaccinedetial, 'vaccinationDate5')
                                ? moment(vaccinedetial.vaccinationDate5)
                                : null,
                              rules: [
                                {
                                  required: false,
                                  message: formatMessage(
                                    'applicationCommon.workerCard.expiredDate.vaccineErr',
                                  ),
                                },
                              ],
                            })(
                              <DatePicker
                                onChange={(date, dateString) => this.onChange(date, dateString, 5)}
                                disabled={
                                  !(
                                    form.getFieldValue('vaccination_date1') &&
                                    form.getFieldValue('vaccination_date2') &&
                                    form.getFieldValue('vaccination_date3') &&
                                    form.getFieldValue('vaccination_date4')
                                  )
                                }
                                format={formatMessage('datetimeFormat.date')}
                              />,
                            )}
                          </Form.Item>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Form>
          </div>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
